package com.mkr.servlet;


import com.mkr.service.UserService;
import com.mkr.service.impl.UserServiceImpl;
import com.mkr.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author mkr
 * @version V1.0
 * @Project BookApp
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/13 21:56
 */
@WebServlet(name = "LoginServlet" , urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码问题
        request.setCharacterEncoding("utf-8");
        //获取前端传入的数据
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");

        //从session中获取储存的验证码
        HttpSession session = request.getSession();
        String validateCode = (String)session.getAttribute("validateCode");
        //首先判断验证码是否为空
        if (MyUtil.isEmpty(validateCode)){
            response.getWriter().println("请输入验证码");
            //为空，重定向到登录界面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //判断验证码是否正确
        if (!code.equals(validateCode)){
            //验证码不正确，重定向到登录界面
            response.getWriter().println("验证码有误");
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //判断用户名、密码是否为空
        if (MyUtil.isEmpty(uname)&& MyUtil.isEmpty(pwd)){
            //任意一个为空或两个都为空，重定位到登录界面
            response.getWriter().println("用户名或密码不能为空");
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //验证码正确、用户名、密码不为空
        //执行登录操作、调用业务层的内容
        UserService service = new UserServiceImpl();
        //判断用户名、密码是否正确
        boolean result = service.login(uname,pwd);

        if (result){
            //记录登录信息
            session.setAttribute("uname", uname);
            //登录成功-跳转
            response.sendRedirect(request.getContextPath()+"/bookList");
        }else{
            response.getWriter().println("用户名或密码有误");
            //登录失败，重定向到登录界面
            response.sendRedirect(request.getContextPath()+"/login.html");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
